<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="字典类型" prop="dType">
        <el-input v-model="queryParams.dType" placeholder="请输入字典类型" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否内置" prop="type">
        <el-select v-model="queryParams.type" placeholder="是否内置">
          <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker 
          v-model="dateRange" 
          type="daterange" 
          range-separator="-" 
          start-placeholder="开始日期" 
          end-placeholder="结束日期"
          @change="handleDateChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd" v-hasPermi="['admin:dict:add']"> {{ $t('btn.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate" v-hasPermi="['admin:dict:edit']">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['admin:dict:remove']">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 字典表格（已添加“是否内置”列） -->
    <el-table 
      :data="typeList" 
      v-loading="loading" 
      border 
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange" 
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column 
        label="字典编号" 
        align="center" 
        prop="id" 
        width="100" 
        sortable 
      />
      <el-table-column label="字典类型" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-link type="primary" @click="showDictData(scope.row)">{{ scope.row.dType }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- 新增：是否内置列 -->
      <el-table-column label="是否内置" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button text size="small" icon="edit" @click="handleUpdate(scope.row)" v-hasPermi="['admin:dict:edit']">
            {{ $t('btn.edit') }}
          </el-button>
          <el-button text size="small" icon="delete" @click="handleDelete(scope.row)" v-hasPermi="['admin:dict:remove']">
            {{ $t('btn.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination 
      v-show="total > 0" 
      :total="total" 
      v-model:page="queryParams.pageNum" 
      v-model:limit="queryParams.pageSize" 
      @pagination="getList" 
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" draggable width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dType">
          <template #label>
            <span>
              <el-tooltip content="如果从数据库加载数据，请使用sql_开头字符串" placement="top">
                <el-icon :size="15">
                  <questionFilled />
                </el-icon>
              </el-tooltip>
              字典类型
            </span>
          </template>
          <el-input v-model="form.dType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="字典状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :value="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="系统内置" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button v-for="dict in typeOptions" :key="dict.dictValue" :value="dict.dictValue">{{ dict.dictLabel }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="自定义sql" prop="customSql">
          <template #label>
            <span>
              <el-tooltip
                content="如果从数据库加载数据，请按此格式配置sql语句：SELECT userId as dictValue, userName as dictLabel FROM sys_user"
                placement="top">
                <el-icon :size="15">
                  <questionFilled />
                </el-icon>
              </el-tooltip>
              sql语句
            </span>
          </template>
          <el-input v-model="form.customSql" type="textarea" placeholder="请输入sql语句"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

    <!-- 字典数据子组件对话框 -->
    <el-dialog v-model="dictDataVisible" draggable width="60%" :lock-scroll="false">
      <dict-data v-model:dictId="dictId"></dict-data>
    </el-dialog>
  </div>
</template>

<script setup name="dict">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import dictData from '@/views/components/dictData'
import { listType, getType, delType, addType, updateType } from '@/api/system/dict/type'

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 状态变量
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const typeList = ref([])
const title = ref('')
const open = ref(false)
const dictDataVisible = ref(false)
const statusOptions = ref([])
const typeOptions = ref([])
const dateRange = ref([]) // 日期范围数组
const formRef = ref()
const dictId = ref(0)

// 响应式数据
const state = reactive({
  rules: {
    dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
    dType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
  },
  form: {
    id: undefined,
    dictName: undefined,
    dType: undefined,
    status: '0',
    type: 'N',
    remark: undefined,
    customSql: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dType: undefined,
    status: undefined,
    type: undefined,
    Sort: undefined,
    SortType: undefined,
    CreateTimeStart: undefined,
    CreateTimeEnd: undefined
  }
})
const { rules, form, queryParams } = toRefs(state)

/** 日期范围变化：拆分日期数组为两个参数 */
function handleDateChange() {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.CreateTimeStart = dateRange.value[0]
    queryParams.value.CreateTimeEnd = dateRange.value[1]
  } else {
    queryParams.value.CreateTimeStart = undefined
    queryParams.value.CreateTimeEnd = undefined
  }
}

/** 查询字典类型列表 */
function getList() {
  loading.value = true
  listType(queryParams.value).then((response) => {
    typeList.value = response.data.result
    total.value = response.data.totalNum
    loading.value = false
  })
}

/** 排序事件处理 */
function handleSortChange(sort) {
  if (sort.order) {
    queryParams.value.Sort = sort.column.prop
    queryParams.value.SortType = sort.order === 'asc' ? 'ascending' : 'descending'
  } else {
    queryParams.value.Sort = undefined
    queryParams.value.SortType = undefined
  }
  getList()
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictName: undefined,
    dType: undefined,
    status: '0',
    type: 'N',
    remark: undefined,
    customSql: undefined
  }
  proxy.resetForm('formRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value.CreateTimeStart = undefined
  queryParams.value.CreateTimeEnd = undefined
  proxy.resetForm('queryForm')
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加字典类型'
}

/** 多选框选中事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const dictId = row?.id || ids.value[0]
  getType(dictId).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改字典类型'
  })
}

/** 提交表单 */
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        updateType(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addType(form.value).then(() => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const dictIds = row?.id ? row.id : ids.value.join(',')
  proxy
    .$confirm(`是否确认删除字典编号为"${dictIds}"的数据项?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => delType(dictIds))
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
}

/** 查看字典数据 */
function showDictData(row) {
  dictId.value = row.id
  dictDataVisible.value = true
}

// 初始化加载
getList()
// 加载状态字典
proxy.getDicts('sys_normal_disable').then((response) => {
  statusOptions.value = response.data
})
// 加载是否内置字典
proxy.getDicts('sys_yes_no').then((response) => {
  typeOptions.value = response.data
})
</script>